package com.cy.hui_jie_dan.interceptor;


import com.cy.hui_jie_dan.comon.constant.JwtClaimsConstant;
import com.cy.hui_jie_dan.comon.context.BaseContext;
import com.cy.hui_jie_dan.comon.properties.JwtProperties;
import com.cy.hui_jie_dan.comon.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());
        log.info("Received token from header: {}", token);

        if (token == null || token.isEmpty()) {
            log.error("Token is null or empty");
            response.setStatus(401);
            return false;
        }

        //2、校验令牌
        try {
            log.info("开始jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            if (claims == null) {
                log.error("Failed to parse JWT token");
                response.setStatus(401);
                return false;
            }

            Object userIdObj = claims.get(JwtClaimsConstant.USER_ID);
            if (userIdObj == null) {
                log.error("USER_ID not found in token claims");
                response.setStatus(401);
                return false;
            }

            Long userId = Long.valueOf(userIdObj.toString());
            log.info("当前用户ID：{}", userId);
            
            // 验证Redis中的token是否与当前token一致
            String redisKey = "user_token:" + userId;
            String storedToken = (String) redisTemplate.opsForValue().get(redisKey);
            if (storedToken == null || !storedToken.equals(token)) {
                log.error("Token已失效或已在其他设备登录，用户ID: {}, 存储的token: {}, 当前token: {}", 
                    userId, storedToken, token);
                response.setStatus(401);
                return false;
            }
            
            // 设置当前用户ID到上下文
            BaseContext.setCurrentId(userId);
            log.info("Successfully set current user ID in context");
            
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            log.error("JWT验证失败: {}", ex.getMessage(), ex);
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
